package org.eclipse.moquette.parser.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import org.eclipse.moquette.proto.messages.AbstractMessage;
import org.eclipse.moquette.proto.messages.SubscribeMessage;

/**
 * 订阅的byte1 后4位必须是0 0 1 0
 *
 * Created by alex on 15-5-26.
 */
public class SubscribeEncoder extends DemuxEncoder<SubscribeMessage> {

    @Override
    protected void encode(ChannelHandlerContext ctx, SubscribeMessage message, ByteBuf out) {

        if (message.subscriptions().isEmpty()) {
            throw new IllegalArgumentException("Found a subscribe message with empty topics");
        }

        if (message.getQos() != AbstractMessage.QOSType.LEAST_ONE) {
            throw new IllegalArgumentException("Expected a message with Qos 1, found " + message.getQos());
        }

        ByteBuf variableHeaderBuff = ctx.alloc().buffer(4);
        ByteBuf buff = null;

        try {

            //写入可变头部 Message ID部分
            variableHeaderBuff.writeShort(message.getMessageID());

            //写入 Payload  topic filter部分
            for (SubscribeMessage.Couple c : message.subscriptions()) {
                variableHeaderBuff.writeBytes(Utils.encodeString(c.getTopicFilter()));
                variableHeaderBuff.writeByte(c.getQos());
            }


            int variableHeaderSize = variableHeaderBuff.readableBytes();
            byte flags = Utils.encodeFlags(message);
            buff = ctx.alloc().buffer(2 + variableHeaderSize);

            buff.writeByte(AbstractMessage.SUBSCRIBE << 4 | flags);
            buff.writeBytes(Utils.encodeRemainingLength(variableHeaderSize));
            buff.writeBytes(variableHeaderBuff);

            out.writeBytes(buff);
        }finally {
            variableHeaderBuff.release();
            buff.release();
        }
    }

}
